//
//  IATViewController.m
//  VoiceClass
//
//  Created by caoxiaobo on 2017/9/2.
//  Copyright © 2017年 YRX. All rights reserved.
//

#import "IATViewController.h"
#import <iflyMSC/IFlyMSC.h>
#import "IATConfig.h"
#import "ISRDataHelper.h"

@interface IATViewController () <IFlySpeechRecognizerDelegate>

@property (weak, nonatomic) IBOutlet UIButton *recordButton;
@property (weak, nonatomic) IBOutlet UIButton *cancelRecordButton;
@property (weak, nonatomic) IBOutlet UIButton *stopRecordButton;
@property (weak, nonatomic) IBOutlet UITextView *contentTextView;

@property (strong, nonatomic) NSString *pcmFilePath;

@property (nonatomic, strong) IFlySpeechRecognizer *speechRecognizer;
@property (nonatomic,strong) IFlyPcmRecorder *pcmRecorder;//录音器，用于音频流识别的数据传入

@end

@implementation IATViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 录音保存路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [paths objectAtIndex:0];
    _pcmFilePath = [[NSString alloc] initWithFormat:@"%@",[cachePath stringByAppendingPathComponent:@"asr.pcm"]];
}

- (void)viewWillDisappear:(BOOL)animated {
    [_speechRecognizer cancel]; //取消识别
    [_speechRecognizer setDelegate:nil];
    [_speechRecognizer setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
}

- (void)viewWillAppear:(BOOL)animated {
    [self initRecognizer];
}

- (IBAction)record:(id)sender {
    [self.contentTextView setText:@""];
    [self.contentTextView resignFirstResponder];
    
    if(self.speechRecognizer == nil)
    {
        [self initRecognizer];
    }
    [self.speechRecognizer cancel];
    
    //设置音频来源为麦克风
    [self.speechRecognizer setParameter:IFLY_AUDIO_SOURCE_MIC forKey:@"audio_source"];
    //设置听写结果格式为json
    [self.speechRecognizer setParameter:@"json" forKey:[IFlySpeechConstant RESULT_TYPE]];
    //保存录音文件，保存在sdk工作路径中，如未设置工作路径，则默认保存在library/cache下
    [self.speechRecognizer setParameter:@"asr.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];
    [self.speechRecognizer setDelegate:self];
    
    BOOL ret = [self.speechRecognizer startListening];
    if (ret) { // 成功
        
    }else{
        // 可能是上次请求未结束，暂不支持多路并发
        // 处理 error
    }
}

- (IBAction)cancelRecord:(id)sender {
    [self.speechRecognizer cancel];
}

- (IBAction)stopRecord:(id)sender {
    [self.speechRecognizer stopListening];
}

#pragma mark - IFlySpeechRecognizerDelegate

- (void) onError:(IFlySpeechError *) errorCode {
    int code = errorCode.errorCode;
    NSString *msg = errorCode.errorDesc;
    NSLog(@"error--Code: %@, msg: %@", @(code), msg);
}

- (void) onResults:(NSArray *) results isLast:(BOOL)isLast {
    NSMutableString *resultString = [[NSMutableString alloc] init];
    NSDictionary *dic = results[0];
    for (NSString *key in dic) {
        [resultString appendFormat:@"%@",key];
    }
    
    NSString * resultFromJson =  [ISRDataHelper stringFromJson:resultString];
    self.contentTextView.text = [NSString stringWithFormat:@"%@%@", self.contentTextView.text,resultFromJson];
    
    if (isLast){
        
    }
}

-(void)initRecognizer
{
        //单例模式，无UI的实例
        if (_speechRecognizer == nil) {
            _speechRecognizer = [IFlySpeechRecognizer sharedInstance];
            [_speechRecognizer setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
            //设置听写模式
            [_speechRecognizer setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
        }
        _speechRecognizer.delegate = self;
        
        if (_speechRecognizer != nil) {
            IATConfig *instance = [IATConfig sharedInstance];
            //设置最长录音时间
            [_speechRecognizer setParameter:instance.speechTimeout forKey:[IFlySpeechConstant SPEECH_TIMEOUT]];
            //设置后端点
            [_speechRecognizer setParameter:instance.vadEos forKey:[IFlySpeechConstant VAD_EOS]];
            //设置前端点
            [_speechRecognizer setParameter:instance.vadBos forKey:[IFlySpeechConstant VAD_BOS]];
            //网络等待时间
            [_speechRecognizer setParameter:@"20000" forKey:[IFlySpeechConstant NET_TIMEOUT]];
            //设置采样率，推荐使用16K
            [_speechRecognizer setParameter:instance.sampleRate forKey:[IFlySpeechConstant SAMPLE_RATE]];
            //设置语言
            [_speechRecognizer setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
            //设置方言
            [_speechRecognizer setParameter:instance.accent forKey:[IFlySpeechConstant ACCENT]];
            //设置是否返回标点符号
            [_speechRecognizer setParameter:@"0" forKey:[IFlySpeechConstant ASR_PTT]];
            [_speechRecognizer setParameter:@"0" forKey:[IFlySpeechConstant ASR_PTT_HAVEDOT]];
            [_speechRecognizer setParameter:@"1" forKey:[IFlySpeechConstant ASR_PTT_NODOT]];
        }
        
        //初始化录音器
//        if (_pcmRecorder == nil)
//        {
//            _pcmRecorder = [IFlyPcmRecorder sharedInstance];
//        }
//
//        _pcmRecorder.delegate = self;
//
//        [_pcmRecorder setSample:[IATConfig sharedInstance].sampleRate];
//
//        [_pcmRecorder setSaveAudioPath:nil];    //不保存录音文件
    
}

@end
